/**************************************************************************************************
 * Name: MeasureCalcSearchController
 * Object: Agent_Order__c
 * Purpose: 检索试剂，选择产品，批量添加到测算信息产品中
 * Requirement:
 * Author: Sera
 * Create Date: 2017-5-24
 * Modify History:

***************************************************************************************************/
public with sharing class MeasureCalcSearchController {

    //测算信息产品对象集合
    public List<MeasureCalculateProductBean> mcpList { get; set; }
    public List<ProductBean> pbList { get; set; }
    public List<MeasureCalculateProductBean> cpList {get;set;}
    // public Boolean Approve{get;set;}
    // public Measure_Calculate__c  measure{ get; set; }

    public String name { get; set; }
    public String brand { get; set; }
    public String serial { get; set; }
    public String category0 { get; set; }
    public String category1 { get; set; }
    public String typeName {get; set;}//产品类型

    public List<SelectOption> cate0Opts { get; private set; }
    public List<SelectOption> cate1Opts { get; private set; }
    // public List<SelectOption> corpcodeOpts { get; private set; }
    // public List<SelectOption> vsalestrucodeOpts { get; private set; }

    public String mId { get; private set; }  // 测试信息Id
    public User u { get; private set ; }
    // public String oppId { get; private set; }  // 业务机会Id
    // public String type { get; private set; }
    // public Boolean cantSeeLowFlg { get; private set; }
     public Boolean isApproaling { get; private set;}//是否在审批中
    public Measure_Calculate__c mc ;
    public Boolean cantSeeYield { get; private set ; }

    private User user;
    private Opportunity opp;

    public Boolean isSuccess {get;set;}
    //----------------------------------------------------------------
    public Boolean isShowCPSelect {get;private set;}
    public List<SelectOption> categorys { get; private set; }
    public List<SelectOption> products { get; private set; }
    public List<SelectOption> brands { get; private set; }
    public List<SelectOption> serials { get; private set; }
    public  String sealflag ; //公司编码

    public String cpname {get;set;}
    public String cpbrand {get;set;}
    public String cpcate {get;set;}
    public String cpserial {get;set;}

    // private String purpose;

    public MeasureCalcSearchController(ApexPages.StandardController stdController) {
        // Approve = false;
        pbList = new List<ProductBean>();
        mcpList = new List<MeasureCalculateProductBean>();
        cpList = new List<MeasureCalculateProductBean>();
        mId = stdController.getId();
        
        cate0Opts = new List<SelectOption>();
        cate0Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category0.split(',', -1)) {
            cate0Opts.add(new SelectOption(str, str));
        }

        cate1Opts = new List<SelectOption>();
        cate1Opts.add(new SelectOption('', System.Label.Option_None));
        for (String str : System.Label.Product_Category1.split(',', -1)) {
            cate1Opts.add(new SelectOption(str, str));
        }

        cantSeeYield = false;
        mc = new Measure_Calculate__c();

        products = new List<SelectOption>();
        products.add(new SelectOption('', System.Label.Option_None));

        brands = new List<SelectOption>();
        brands.add(new SelectOption('', System.Label.Option_None));

        categorys = new List<SelectOption>();
        categorys.add(new SelectOption('', System.Label.Option_None));

        sealflag = '';

       

    }

    /**
     * 页面跳转查询数据
     */
    public void init() {
      
        u = [select SubCompany__c, Profile.Name from User where Id = :UserInfo.getUserId()];

        // 获取测算产品
        if (String.isBlank(mId) == false) {
             mc = [select Id,LastMeasureCalc__c,Status__c,Company__c ,CopDealer__c,Opportunity__r.CoopDealer__c from Measure_Calculate__c where Id =:mId];
            ///获取测算信息下面的测算产品 
            getMeasureProduct(mId,false);
               ///获取封存标记
        Map<String,String> cm = getPicklistValues('Contract__c','Corpcode__c');
         sealflag = 'Y-'+cm.get(mc.Company__c);
            ///如果测算信息下面没有产品 则获取上次测算的测算产品
            if (mcpList.size() == 0 && mc.LastMeasureCalc__c != null) {
                getMeasureProduct(mc.LastMeasureCalc__c,true);
            }
            //System.debug('==='+ mc.CoopDealer__c);

            if(mc.CopDealer__c != null && mc.Opportunity__r.CoopDealer__c!= null){
                isShowCPSelect = true;
                getProductFromCp();

            }

            if(mc.Status__c == '审批成功' || mc.Status__c == '已提交')isApproaling = true;
            if(isApproaling == true)  ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, '测算提交审批中或审批通过不能修改!'));
        }


        // 销售员及其主管只能填写标本量
        Set<String> profileSet = new Set<String>(System.Label.Rt_CantSeeYield.split(','));
        if (profileSet.contains(u.Profile.Name)) cantSeeYield = true;

        String completion = System.currentPageReference().getParameters().get('c');
        if (String.isBlank(completion) == false) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Save_OK));
        }


        
    }

   
        //获得PickList的值
    public static Map<String, String> getPicklistValues(String sObjectName, String sFieldName){
        Map<String, String> picValues= new Map<String, String>();
        Map<String, Schema.SObjectType> sObjectDescribeMap = Schema.getGlobalDescribe();
        if (sObjectDescribeMap.containsKey(sObjectName)) {
            Map<String, Schema.SobjectField> sObjectFieldsMap = 
               sObjectDescribeMap.get(sObjectName).getDescribe().fields.getMap();
            if (sObjectFieldsMap.containsKey(sFieldName)) {
                Schema.DescribeFieldResult sObjectFieldDescribe = sObjectFieldsMap.get(sFieldName).getDescribe();
                List<Schema.PicklistEntry> lPickEntryList = sObjectFieldDescribe.getPicklistValues();
                for (Schema.PicklistEntry tPicklistEntry : lPickEntryList) {
                    if(tPicklistEntry.isActive() == true){
                        picValues.put(tPicklistEntry.getLabel(),tPicklistEntry.getValue());
                    }
                    /*picValues.put(tPicklistEntry.getValue(), new Map<String,object>{
                        'value' => tPicklistEntry.getValue(),
                        'isActive' => tPicklistEntry.isActive(),
                        'isDefaultValue' => tPicklistEntry.isDefaultValue(),
                        'label' => tPicklistEntry.getLabel()
                    });*/
                }
            } else {
                //TODO 不存在此字段的执行
            }
        } else {
            // TODO 不存在此sObject的执行
        }
        return picValues;
    }
    ///获取测算产品
    public void getMeasureProduct(String mcid,Boolean isLastMeasure){
         Schema.DescribeSobjectResult m = Measure_Calculate_Product__c.sObjectType.getDescribe();
            Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
            
            String sql = 'select  ';
            String fields = '';
            for (String field : fieldMap.keySet()) {
                 if (fields.length() > 0) {
                    fields += ', '; 
                }
                fields += field;
            }

            sql += fields;
            sql += ' , Product__r.NCCode__c,Product__r.name,Product__r.Brand__c,Product__r.SerialNo__c, Product__r.TestNumber__c,Product__r.swjhdj__c,'
                + 'Product__r.Spec__c,Product__r.Category1__c, Product__r.Category2__c from Measure_Calculate_Product__c where Measure_Calculate__c = \'' + mcid + '\' and IsEquipRelated__c != true';
            
            List<Measure_Calculate_Product__c> temp = Database.query(sql);
            Set<Id>  pids= new Set<Id>();
            for (Measure_Calculate_Product__c qp : temp) {
                pids.add(qp.Product__c);
            }
            Map<Id,Price__c> priceMap  = getPriceMap(pids);
            for (Measure_Calculate_Product__c qp : temp) {
                MeasureCalculateProductBean mcpb= new MeasureCalculateProductBean(qp,isLastMeasure,priceMap.get(qp.Product__c));
                mcpList.add(mcpb);
            }

    }
    public void saveAndStay() {
       Savepoint sp = Database.setSavepoint();
        try {
            System.debug('*********保存测算信息产品************');
            // 必须有产品才能保存
            if (mcpList.size() == 0) {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING, '请选择产品'));
                return ;
            }
           


            // 获取价格信息
          /*  List<Id> pIdList = new List<Id>();
            for (MeasureCalculateProductBean mcp : mcpList) {
                if (String.isBlank(mcp.productId) == false) {
                    pIdList.add(mcp.productId);
                }
            }
            Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
            for (Price__c pr : [select Id, Product__c, MarketPrice__c, HospitalManagerPrice__c, HospitalBottomPrice__c, CompanyBottomPrice__c, Taxrate__c,
                AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c ,LastMonthAveragePrice__c from Price__c where Product__c in : pidList and Company__c = :u.SubCompany__c]) {
                priceMap.put(pr.Product__c, pr);
            }*/

        


            // TODO 不用delete/insert，考虑update

            // 测算产品delete
            List<Measure_Calculate_Product__c> delList = [select Id from Measure_Calculate_Product__c where Measure_Calculate__c= :mId and Product__r.Category0__c !='仪器'];
            if (delList.size() > 0) delete delList;

            // 测算产品insert
            List<Measure_Calculate_Product__c> insList = new List<Measure_Calculate_Product__c>();
            for (MeasureCalculateProductBean mcpb : mcpList) {

              

                insList.add(
                    new Measure_Calculate_Product__c(
                        Measure_Calculate__c = mId,
                        Product__c = mcpb.productId,
                        TestNum__c = mcpb.testNum,
                        CompanyBottomPrice__c = mcpb.CompanyBottomPrice,
                        HospitalBottomPrice__c = mcpb.HospitalBottomPrice,
                        UnitPriceWT__c = mcpb.UnitPriceWT,
                        TaxRate__c = mcpb.TaxRate,
                       // Volume__c = mcpb.volume,
                        SampleNum1__c = mcpb.sampleNum1,
                        SalesPriceWT__c = mcpb.salesPriceWT,
                        NowEsti__c = mcpb.nowEsti,
                        Category0__c = mcpb.category0,
                        ProductLine__c = mcpb.prodLine,
                        Brand__c = mcpb.brand,
                        LastPrice__c = mcpb.lastPrice,

                        InstCost__c = mcpb.groupCost ,//集团成本(价格 成本价)
                        DealerInstCost__c = mcpb.dealerCost,
                        SubInstCost__c  = mcpb.subCost

                        // SampleNum1__c = mcpb.sampleNum1,
                        // NowEsti__c = mcpb.type,
                        // Index__c = mcpb.index
                    )
                );
            }
            insert insList;
            isSuccess = true;
           // PageReference ref = new PageReference('/apex/MeasureCalcInput?id=' + mId + '&c=1');
            //ref.setRedirect(true);
            //return ref;
            // ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, System.Label.Save_OK));
        } catch (Exception e) {
            Database.rollback(sp);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
        
        return ;
    }

    /**
     * 检索产品
     */
    public void search() {
        String whereStr = '';
        pbList = new List<ProductBean>();
        
        System.debug('*******检索产品**************');
        if (String.isBlank(name) == false) {
            whereStr += ' and Name like \'%' + name + '%\'';
        }
        if (String.isBlank(brand) == false) {
            whereStr += ' and  Brand__c like \'%' + brand + '%\'';
        }
        if (String.isBlank(serial) == false) {
            whereStr += ' and  SerialNo__c like \'%' + serial + '%\'';
        }
  
        if (String.isBlank(category1) == false) {
            whereStr += ' and  Category1__c = \'' + category1 + '\'';
        }
        if (String.isBlank(typeName) == false) {
            whereStr += ' and  TypeName__c like \'%' + typeName + '%\'';
        }
        whereStr += ' and Category0__c!=\'仪器\'';
       
        List<Product__c> plist = Database.query(this.soqlStr() + whereStr + ' limit 500');
      
        // 获取价格信息
        Set<Id> pidList = new Set<Id>();
        for (Product__c p : plist) {
            if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))pidList.add(p.Id);
        }

       

        Map<Id, Price__c> priceMap = getPriceMap(pIdList);

        for (Product__c p : plist) {
          
            if(!(p.SealCompany__c != null && p.SealCompany__c.contains(sealflag)))pbList.add(new ProductBean(p, priceMap.get(p.Id)));
        }

        
    }
    /**
    *如果经销商不为空的时候  测算产品可以从合同产品里面选择，选不到的从产品中选择，取有效的合同，业务机会下的合作经销商的有效且未终止的合同
    */
    public void getProductFromCp(){

        String sql = 'select Id ,Name,Product__r.Brand__c,Product__r.Category1__c,Product__r.Name ,Product__c ,SalesPrice__c,Product__r.SealCompany__c ,  ';
        sql += ' Product__r.SerialNo__c,Product__r.Category0__c,Product__r.Category2__c,Product__r.Spec__c,Product__r.swjhdj__c ,Product__r.TestNumber__c ';
        sql+= ' from ContractProduct__c where Contract__r.Status__c =\'已生效\' and Contract__r.Stopped__c = false and Contract__r.Account__c =\''+mc.Opportunity__r.CoopDealer__c+'\' ';

        sql += ' and Product__r.Category0__c = \'试剂\' ';
System.debug('==='+sql);

        List<ContractProduct__c> temp  = Database.query(sql);

        if (String.isBlank(cpname) == false) {
            sql += ' and Product__r.Name like \'%' + cpname + '%\'';
        }
        if (String.isBlank(cpbrand) == false) {
            sql += ' and  Product__r.Brand__c like \'%' + cpbrand + '%\'';
        }
        if (String.isBlank(cpcate) == false) {
            sql += ' and  Product__r.Category1__c like \'%' + cpcate + '%\'';
        }
        if (String.isBlank(cpserial) == false) {
            sql += ' and  Product__r.SerialNo__c like \'%' + cpserial + '%\'';
        }
        sql += ' limit 500';
        ///生成选项列表

         Set<String> ps = new Set<String>();
        Set<String> bs = new Set<String>();
        Set<String> cas = new Set<String>();
        Set<String> ses = new Set<String>();
        Set<Id> pids = new Set<Id>();
        for(ContractProduct__c cp : temp){
            pids.add(cp.Product__c);
            if(cp.Product__r.Name != null)ps.add(cp.Product__r.Name);
            if(cp.Product__r.Brand__c != null)bs.add(cp.Product__r.Brand__c);
            if(cp.Product__r.Category1__c != null)cas.add(cp.Product__r.Category1__c);
            if(cp.Product__r.SerialNo__c != null)ses.add(cp.Product__r.SerialNo__c);
        }
        products = optionHandler(ps);
        brands = optionHandler(bs);
        categorys = optionHandler(cas);
        serials = optionHandler(ses);
        Map<Id,Price__c> priceMap = getPriceMap(pids);
        cpList.clear();
        for (ContractProduct__c cp  : temp) {
            if(!(cp.Product__r.SealCompany__c != null && cp.Product__r.SealCompany__c.contains(sealflag)))cpList.add(new MeasureCalculateProductBean(cp,priceMap.get(cp.Product__c)));
        }


    }
    ///生成 选项列表
    private List<SelectOption>  optionHandler (Set<String> s){
       List<SelectOption> ss = new List<SelectOption>();
       ss.add(new SelectOption('', System.Label.Option_None));

        for (String str : s){
        ss.add(new SelectOption(str,str));
        }
        return ss;
    }
    ///获取价格
    private Map<Id,Price__c> getPriceMap (Set<Id> pidList){
        System.debug(pIdList+'\n' + mc.Company__c);
         Map<Id, Price__c> priceMap = new Map<Id, Price__c>();
         for (Price__c pr : [select Id, Product__c, MarketPrice__c, AreaDealerPrice__c, InvoiceDealerPrice__c, RepairCost__c, InstCost__c,HospitalManagerPrice__c
                                    ,HospitalBottomPrice__c,CompanyBottomPrice__c,TaxRate__c from Price__c 
                                     where Product__c in : pidList and Company__c = :mc.Company__c]) {
                    priceMap.put(pr.Product__c, pr);
        }
        System.debug('+++'+priceMap);

        return priceMap;


    }


    /**
     * 交换上下栏选中的产品
     */
    public void exchange() {

        System.debug('**********交换产品***********');
        // 去掉已勾选的测算产品
        List<MeasureCalculateProductBean> stayList = new List<MeasureCalculateProductBean>();
        for (MeasureCalculateProductBean mcp : mcpList) {
            if (mcp.chk == false) {
                stayList.add(mcp);
            }
        }
        mcpList.clear();
        mcpList.addAll(stayList);

        // 收集已选测算产品的产品Id
        Set<Id> existPid = new Set<Id>();
        for (MeasureCalculateProductBean mcp : mcpList) {
            existPid.add(mcp.productId);
        }
        // 加入已勾选的产品
        for (ProductBean p : pbList) {
            if (p.chk == true && existPid.contains(p.rec.Id) == false) {
                mcpList.add(new MeasureCalculateProductBean(p.rec,p.pr));
                existPid.add(p.rec.Id);
                p.chk = false;
            }
        }

        for (MeasureCalculateProductBean mcp : cpList) {
             if (mcp.chk == true && existPid.contains(mcp.productId) == false) {
                mcpList.add(mcp);
                existPid.add(mcp.productId);
                mcp.chk = false;
            }
        }
        
  
    }
/*
    // 填写标本量信息画面
    public PageReference saveAndEstimate() {
        try {
            this.saveAndStay();
            PageReference ref = new PageReference('/apex/MeasureCalcInput?id=' + mId);
            ref.setRedirect(true);
            
            return ref;
        } catch (Exception e) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
        return null;
    }
    */
/*
    // 子公司画面
    public PageReference saveAndEstimate2() {
        try {
            this.saveAndStay();
            PageReference ref = new PageReference('/apex/MeasureCalcCompany?id=' + mId);
            ref.setRedirect(true);
            
            return ref;
        } catch (Exception e) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
        return null;
    }

    // 集团画面
    public PageReference saveAndEstimate3() {
        try {
            this.saveAndStay();
            PageReference ref = new PageReference('/apex/MeasureCalcGroup?id=' + mId);
            ref.setRedirect(true);
            
            return ref;
        } catch (Exception e) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR, e.getMessage()));
        }
        return null;
    }
*/
    /**
     * 获取产品查询sql语句
     * return [description]
     */
   private String soqlStr() {
        Schema.DescribeSobjectResult m = Product__c.sObjectType.getDescribe();
        Map<String, Schema.SObjectField> fieldMap = m.fields.getMap();
        
        String sql = 'select ';
        String fields = '';
        for (String field : fieldMap.keySet()) {
            if (fields.length() > 0) {
                fields += ', '; 
            }
            fields += field;
        }
        sql += fields;
        sql += ' from Product__c where name != null  ';

        return sql;
    }
    

    /**
     * 测算商品自定义对象（用于页面数据展示保存）
     */
    public class MeasureCalculateProductBean {
       public Measure_Calculate_Product__c measure_Calculate_Product { get; set; }
        public String producName { get; set; }
        public Product__c product { get; set; }
        public Decimal testNum { get; set; }
        public Decimal volume { get; set; }
        public Decimal sampleNum1 { get; set; }
        public Decimal salesPriceWT { get; set; }
        public String brand { get; set; }
        public String serialNo { get; set; }
        public String spec { get; set; }
        public String category1 { get; set; }
        public String category2 { get; set; }
        public String nowEsti { get; set; }
        public Boolean chk { get; set; }
        public Id productId { get; set; }
        public String prodLine {get;set;}
        public Decimal lastPrice {get; set;}//上次测算价格

        public Decimal subCost ;//子公司成本
        public Decimal groupCost ;//迈克成本
        public Decimal dealerCost ;//经销商成本
        public Decimal CompanyBottomPrice;
        public Decimal HospitalBottomPrice;
        public Decimal LastMonthAveragePrice;
        public Decimal UnitPriceWT;
        public Decimal TaxRate;
      
        public String category0 {get;set;} //主分类

        public MeasureCalculateProductBean(Measure_Calculate_Product__c record,Boolean isFromLastMeasure,Price__c pr ) {
            measure_Calculate_Product = record;
            producName = record.Product__r.Name;
            serialNo=record.Product__r.SerialNo__c;
            spec=record.Product__r.Spec__c;
            category1=record.Product__r.Category1__c;
            category2=record.Product__r.Category2__c;
            // product = record.Product__r;
            productId = record.Product__c;
            chk = false;
            testNum = record.TestNum__c;
            //volume = record.Volume__c;
            sampleNum1 = record.SampleNum1__c;
            salesPriceWT = record.SalesPriceWT__c;
            nowEsti = record.NowEsti__c;
            category0 = record.Category0__c;
            prodLine = record.ProductLine__c;
            brand = record.Product__r.Brand__c;
            TaxRate =  pr == null ? 0 : pr.TaxRate__c == null ? 0: pr.TaxRate__c;

            subCost = pr == null ? 0 : pr.InstCost__c;
            groupCost = (record.Product__r.Brand__c != null && record.Product__r.Brand__c.contains('迈克')) ? (record.Product__r.swjhdj__c != null  ? record.Product__r.swjhdj__c *(1+TaxRate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c ); 

            //groupCost = (record.Product__r.Brand__c != null && record.Product__r.Brand__c.contains('迈克')) ? record.Product__r.swjhdj__c : (pr == null ? 0 : pr.InstCost__c ); 
            dealerCost = pr == null ? 0 : record.DealerInstCost__c;


            //subCost = pr == null ? 0 : pr.InstCost__c;
            //groupCost = record.Product__r.swjhdj__c; 
           //dealerCost  = pr == null ? 0 : pr.AreaDealerPrice__c;

            CompanyBottomPrice= record.CompanyBottomPrice__c;
            HospitalBottomPrice = record.HospitalBottomPrice__c;
            UnitPriceWT =  pr == null ? 0 : pr.MarketPrice__c;
            ///如果是来自上次测算信息 则保存上次测算价格
            lastPrice=isFromLastMeasure ? record.SalesPriceWT__c: record.LastPrice__c;

            ///试剂成本价  
            
        }

        public MeasureCalculateProductBean(Product__c record,Price__c pr) {
            product = record;
            producName = record.Name;
            brand=record.Brand__c;
            serialNo=record.SerialNo__c;
            spec=record.Spec__c;
            category1=record.Category1__c;
            category2=record.Category2__c;
            productId = record.Id;
            chk = false;
            testNum = record.TestNumber__c;
            //volume = record.Volume__c;
            sampleNum1 = 0;
            salesPriceWT = 0;
            nowEsti = '现有';
            category0 = record.Category0__c;
             prodLine = record.Category1__c;
            //迈克测算结果，试剂成本价自产带生物计划单价，非自产带子公司成本价 
            //测算：试剂：迈克利润结果--生物计划单价，子公司利润结果---价格体系的成本价，经销商利润结果---区域经销商价
            subCost = pr == null ? 0 : pr.InstCost__c;
          //  dealerCost = pr == null ? 0 : pr.AreaDealerPrice__c;

            CompanyBottomPrice=  pr == null ? 0 :pr.CompanyBottomPrice__c;
            HospitalBottomPrice =  pr == null ? 0 : pr.HospitalBottomPrice__c;
            UnitPriceWT =  pr == null ? 0 : pr.MarketPrice__c;
            TaxRate =  pr == null ? 0 : pr.TaxRate__c == null ? 0: pr.TaxRate__c;
            groupCost = (record.Brand__c != null && record.Brand__c.contains('迈克')) ? (record.swjhdj__c != null  ? record.swjhdj__c *(1+TaxRate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c ); 


        }

        public MeasureCalculateProductBean (ContractProduct__c record,Price__c pr){
            //product = record.Product__c;

            producName = record.Product__r.Name;
            brand=record.Product__r.Brand__c;
            serialNo=record.Product__r.SerialNo__c;
            spec=record.Product__r.Spec__c;
            category1=record.Product__r.Category1__c;
            category2=record.Product__r.Category2__c;
            productId = record.Product__c;
            chk = false;
            testNum = record.Product__r.TestNumber__c;
            //volume = record.Volume__c;
            sampleNum1 = 0;
            salesPriceWT = 0;
            nowEsti = '现有';
            category0 = record.Product__r.Category0__c;
            prodLine = record.Product__r.Category1__c;
            TaxRate =  pr == null ? 0 : pr.TaxRate__c == null ? 0: pr.TaxRate__c;

            //迈克测算结果，试剂成本价自产带生物计划单价，非自产带子公司成本价 
            //测算：试剂：迈克利润结果--生物计划单价，子公司利润结果---价格体系的成本价，经销商利润结果---区域经销商价
            subCost = pr == null ? 0 : pr.InstCost__c;
             groupCost = (record.Product__r.Brand__c != null && record.Product__r.Brand__c.contains('迈克')) ? (record.Product__r.swjhdj__c != null  ? record.Product__r.swjhdj__c *(1+TaxRate/100.0):null ) : (pr == null ? 0 : pr.InstCost__c ); 

            //groupCost = (record.Product__r.Brand__c != null && record.Product__r.Brand__c.contains('迈克')) ? record.Product__r.swjhdj__c : (pr == null ? 0 : pr.InstCost__c ); 
            dealerCost = pr == null ? 0 : record.SalesPrice__c;

            CompanyBottomPrice=  pr == null ? 0 :pr.CompanyBottomPrice__c;
            HospitalBottomPrice =  pr == null ? 0 : pr.HospitalBottomPrice__c;
            UnitPriceWT =  pr == null ? 0 : pr.MarketPrice__c;

        }

        
       
    }


    public class ProductBean {
        public Product__c rec { get; set; }
        public Price__c pr { get; set; }
        public Decimal marketPrice { get; set; }
        public Boolean chk { get; set; }

        public ProductBean(Product__c record, Price__c price) {
            rec = record;
            pr = price;
            if (price != null) {
                marketPrice = price.AreaDealerPrice__c;
            } else {
                marketPrice = 0;
            }
            chk = false;
        }
        
    }
}